<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  NInput,
  NSelect,
  NDatePicker,
  type DataTableColumns,
  NSpace
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import { RecordType } from '@/router/utils'
import { SealApplication_ContractTypeList, SealApplication_RelatedMoney, SealApplication_MoneyTypeOptions } from '@/enums/index'
import dayjs from 'dayjs'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: '编号',
    key: 'contractNumber',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '年份',
    key: 'year',
    width: 50,
    align: useStore.isCenter
  },
  {
    title: '盖章时间',
    key: 'categoryTime',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '合同名称',
    key: 'docContractName',
    width: 100,
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: 400
        }
      }
    }
  },
  {
    title: '合同类型',
    key: 'contract',
    width: 60,
    align: useStore.isCenter,
    render(e: any) {
      if (!e.contract) {
        return ''
      }
      const re = SealApplication_ContractTypeList.find(s => {
        return s.value === e.contract
      })
      if (!re) {
        return ''
      }
      return re.label
    }
  },
  {
    title: '相对方名称',
    key: 'sideName',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '份数',
    key: 'chapterCategoryNum',
    width: 50,
    align: useStore.isCenter
  },
  {
    title: '合同履行开始日期',
    key: 'startTime',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '合同履行结束日期',
    key: 'endTime',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '金额(元)',
    key: 'contractAmount',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '主要内容',
    key: 'useInfo',
    width: 100,
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '是否归档',
    key: 'status',
    width: 50,
    align: useStore.isCenter,
    render(e: any) {
      return e.status == 4 ? '是' : '否'
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 60,
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse(e.chapterCategoryCode)
            handleDetail(e)
          }
        },
        {
          default: () => '详情'
        }
      )
    ]
  }
]

//用章类型
const NameList = [
  {
    value: '合同章(非政采云)',
    label: '合同章(非政采云)'
  },
  {
    value: '合同章(政采云)',
    label: '合同章(政采云)'
  },
  {
    value: '法人章/馆章/馆党委章',
    label: '法人章/馆章/馆党委章'
  }
]

//筛选条件
const paginationReactive = reactive({
  contractName: null, // 合同名称
  year: null, // 合同名称
  categoryTime: null, // 盖章时间范围
  contract: null, // 合同类型
  sideName: null,
  startTime: null,
  endTime: null,
  filingFlag: null,
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

//详情
const handleDetail = (val: any) => {
  router.push({
    path: '/OA/Seal/LedgerDetail',
    query: {
      id: val.id
    }
  })
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const contractName = ref()
const typeKey = ref()
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'seal',
    api: 'sealApplicationList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        chapterCategoryName: "合同章",
        contractName: paginationReactive.contractName,
        year: paginationReactive.year ? dayjs(paginationReactive.year).format('YYYY') : null,
        startCategoryTime: paginationReactive.categoryTime ? dayjs(paginationReactive.categoryTime[0]).format('YYYY-MM-DD') : null,
        endCategoryTime: paginationReactive.categoryTime ? dayjs(paginationReactive.categoryTime[1]).format('YYYY-MM-DD') : null,
        contract: paginationReactive.contract,
        startStartTime: paginationReactive.startTime ? dayjs(paginationReactive.startTime[0]).format('YYYY-MM-DD') : null,
        endStartTime: paginationReactive.startTime ? dayjs(paginationReactive.startTime[1]).format('YYYY-MM-DD') : null,
        startEndTime: paginationReactive.endTime ? dayjs(paginationReactive.endTime[0]).format('YYYY-MM-DD') : null,
        endEndTime: paginationReactive.endTime ? dayjs(paginationReactive.endTime[1]).format('YYYY-MM-DD') : null,
        sideName: paginationReactive.sideName,
        filingFlag: paginationReactive.filingFlag,
        statusCode: 'A0605',
        ledger: '1'
      }
    }
  })
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data?.totalCount
  const tmp: any = res.data
  tableData.value = tmp?.list
  tableLoading.value = false
}
const exportTableData = async () => {
  tableLoading.value = true
  const [error, res, headers] = await sendRequest({
    module: 'seal',
    api: 'exportSealApplicationList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        chapterCategoryName: "合同章",
        contractName: paginationReactive.contractName,
        year: paginationReactive.year ? dayjs(paginationReactive.year).format('YYYY') : null,
        startCategoryTime: paginationReactive.categoryTime ? dayjs(paginationReactive.categoryTime[0]).format('YYYY-MM-DD') : null,
        endCategoryTime: paginationReactive.categoryTime ? dayjs(paginationReactive.categoryTime[1]).format('YYYY-MM-DD') : null,
        contract: paginationReactive.contract,
        startStartTime: paginationReactive.startTime ? dayjs(paginationReactive.startTime[0]).format('YYYY-MM-DD') : null,
        endStartTime: paginationReactive.startTime ? dayjs(paginationReactive.startTime[1]).format('YYYY-MM-DD') : null,
        startEndTime: paginationReactive.endTime ? dayjs(paginationReactive.endTime[0]).format('YYYY-MM-DD') : null,
        endEndTime: paginationReactive.endTime ? dayjs(paginationReactive.endTime[1]).format('YYYY-MM-DD') : null,
        sideName: paginationReactive.sideName,
        filingFlag: paginationReactive.filingFlag,
        statusCode: 'A0605',
        ledger: '1'
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, res)
  tableLoading.value = false
}
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1, queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  async () => {
    if (route.path == '/OA/Seal/ledgerManage') {
      await queryTableData()
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)
</script>
<!-- 台账管理——合同章 -->
<template>
  <TableView class="table">
    <template #form>
      <!-- <NSpace justify="space-between"> -->
      <NForm :show-feedback="false" label-placement="left" inline>
        <NSpace>
          <NFormItem label="合同名称:">
            <NInput placeholder="请输入关键字" clearable v-model:value="paginationReactive.contractName" />
          </NFormItem>
          <NFormItem label="年份选择:">
            <NDatePicker style="width: 100px;" v-model:value="paginationReactive.year" type="year" clearable />
          </NFormItem>
          <NFormItem label="盖章时间:">
            <NDatePicker style="width: 300px;" v-model:value="paginationReactive.categoryTime" type="daterange"
              clearable />
          </NFormItem>
          <NFormItem label="合同类型:">
            <NSelect style="width: 150px;" :options="SealApplication_ContractTypeList"
              v-model:value="paginationReactive.contract" placeholder="请选择合同类型" class="commonWidth" clearable />
          </NFormItem>
          <NFormItem label="相对方名称:">
            <NInput placeholder="请输入相对方名称" clearable v-model:value="paginationReactive.sideName" />
          </NFormItem>
          <NFormItem label="合同履行开始时间:">
            <NDatePicker style="width: 300px;" v-model:value="paginationReactive.startTime" type="daterange"
              clearable />
          </NFormItem>
          <NFormItem label="合同履行结束时间:">
            <NDatePicker style="width: 300px;" v-model:value="paginationReactive.endTime" type="daterange" clearable />
          </NFormItem>
          <NFormItem label="是否归档:">
            <NSelect style="width: 150px;" :options="[{ value: 1, label: '是' }, { value: 0, label: '否' }]"
              v-model:value="paginationReactive.filingFlag" class="commonWidth" clearable />
          </NFormItem>
          <NFormItem>
            <NButton type="primary" style="width: 78px; margin-right: 20rem" ghost @click="queryTableData(true)">
              查询
            </NButton>
            <NButton type="primary" style="width: 78px;" ghost @click="exportTableData">
              导出
            </NButton>
          </NFormItem>
        </NSpace>
      </NForm>
      <!-- </NSpace> -->
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}

.commonWidth {
  width: 200rem;
}
</style>
